package com.srwl.mytx.dao;

import android.content.Context;
import android.database.sqlite.SQLiteDatabase;

import com.srwl.mytx.domain.ConversationData;
import com.srwl.mytx.greendao.ContactDao;
import com.srwl.mytx.greendao.ConversationDataDao;
import com.srwl.mytx.greendao.DaoMaster;
import com.srwl.mytx.greendao.MessageDao;
import com.srwl.mytx.greendao.UserDao;
import com.srwl.mytx.parse.UserProfileManager;

import org.greenrobot.greendao.database.Database;

/**
 * Created by dahai2070 on 2018/5/8 0008.
 */

public class MyOpenHelper extends DaoMaster.OpenHelper {


    private static MyOpenHelper instance;

    public MyOpenHelper(Context context, String name) {
        super(context, name);
    }

    public MyOpenHelper(Context context, String name, SQLiteDatabase.CursorFactory factory) {
        super(context, name, factory);
    }

    public MyOpenHelper(Context context) {
        super(context, getUserDatabaseName(), null);
    }

    public static MyOpenHelper getInstance(Context context) {
        if (instance == null) {
            instance = new MyOpenHelper(context.getApplicationContext());
        }
        return instance;
    }

    /**
     * 重新这个升级的方法，是为了 使用MigrationHelper，对原数据进行复制。
     * @param db
     * @param oldVersion
     * @param newVersion
     */
    @Override
    public void onUpgrade(Database db, int oldVersion, int newVersion) {
        MigrationHelper.migrate(db, new MigrationHelper.ReCreateAllTableListener() {
            @Override
            public void onCreateAllTables(Database db, boolean ifNotExists) {
                DaoMaster.createAllTables(db, ifNotExists);
            }
            @Override
            public void onDropAllTables(Database db, boolean ifExists) {
                DaoMaster.dropAllTables(db, ifExists);
            }
        }, ContactDao.class, UserDao.class, ConversationDataDao.class, MessageDao.class);
    }


    private static String getUserDatabaseName() {
        return UserProfileManager.getInstance().getUserPhoneNumber() + ".db";
    }

    public void closeDB() {
        if (instance != null) {
            try {
                SQLiteDatabase db = instance.getWritableDatabase();
                db.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
            instance = null;
        }
    }

}
